Authenticator
·170 words·1 min

Two factor authentication. #
If you are using 2-factor authentication (and you should), you probably know about authenticator apps like Authy, FreeOTP and Google Authenticator.
TOTP #
The algorithm used by these apps is called TOTP (Time-based one-time password), which is based on HOTP (HMAC based OTP algorithm).
The settings are usually scanned from a QR code containing a key uri as defined by google ( https://github.com/google/google-authenticator/wiki/Key-Uri-Format) .
For example:
otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example
import hashlib
import base64
import hmac
import datetime
import time
SECRET = base64.b32decode('JBSWY3DPEHPK3PXP')
DIGITS = 6
PERIOD = 30
def int_to_bytes(n):
result = bytearray()
while n != 0:
result.append(n & 0xFF)
n >>= 8
return bytearray(reversed(result)).rjust(8, b"\0")
def otp(n):
hmac_hash = hmac.digest(SECRET, int_to_bytes(n), hashlib.sha1)
offset = hmac_hash[-1] & 0xF
code = (
(hmac_hash[offset] & 0x7F) << 24
| (hmac_hash[offset + 1] & 0xFF) << 16
| (hmac_hash[offset + 2] & 0xFF) << 8
| (hmac_hash[offset + 3] & 0xFF)
)
str_code = str(10_000_000_000 + (code % 10**DIGITS))
return str_code[-DIGITS:]
def timecode():
return int(time.mktime(datetime.datetime.now().timetuple()) / PERIOD)
print(otp(timecode()))
# compare result with https://totp.danhersam.com/